package io.qifan.desktop.server.application;

import cn.dev33.satoken.stp.StpUtil;
import com.querydsl.jpa.impl.JPAQueryFactory;
import io.qifan.desktop.server.domain.device.Device;
import io.qifan.desktop.server.domain.device.QDevice;
import io.qifan.desktop.server.domain.device.repository.DeviceRepository;
import io.qifan.desktop.server.domain.user.QUser;
import io.qifan.desktop.server.domain.user.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class DeviceApplication {
    private final JPAQueryFactory jpaQueryFactory;
    private final EntityManager entityManager;
    private final DeviceRepository deviceRepository;

    public Device findByDeviceName(String deviceName) {
        Optional<Device> deviceOptional = Optional.ofNullable(jpaQueryFactory.selectFrom(QDevice.device)
                .innerJoin(QDevice.device.user, QUser.user)
                // 过滤条件当前用户id+设备名称
                .where(QUser.user.id.eq(StpUtil.getLoginIdAsLong()),
                        QDevice.device.name.eq(deviceName))
                .fetchFirst());

        return deviceOptional.orElseGet(() -> createDevice(deviceName));
    }

    public Device createDevice(String deviceName) {
        Device device = new Device();
        device.create(deviceName, entityManager.getReference(User.class, StpUtil.getLoginIdAsLong()));
        deviceRepository.save(device);
        return device;
    }
}
